package flc.ast.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.stark.ve.core.SpeedMode;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoSpeedBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoSpeedActivity extends BaseAc<ActivityVideoSpeedBinding> {

    public static String videoPath = "";

    private long videoLength = 0;
    private float currentSpeed = 1.0f;//视频速度

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_speed;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVideoSpeedBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.tvVideoSpeed1.setOnClickListener(this);
        mDataBinding.tvVideoSpeed2.setOnClickListener(this);
        mDataBinding.tvVideoSpeed3.setOnClickListener(this);
        mDataBinding.tvVideoSpeed4.setOnClickListener(this);
        mDataBinding.tvVideoSpeed5.setOnClickListener(this);
        mDataBinding.ivVideoSpeedSave.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivPlayStart:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoSpeedSave://保存
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                saveVideo(videoPath);
                break;
            case R.id.tvVideoSpeed1:
                clearSelect();
                mDataBinding.tvVideoSpeed1.setBackgroundResource(R.drawable.an3);
                mDataBinding.tvVideoSpeed1.setTextColor(Color.parseColor("#FFFFFF"));
                serSpeed(0.5f);
                break;
            case R.id.tvVideoSpeed2:
                clearSelect();
                mDataBinding.tvVideoSpeed2.setBackgroundResource(R.drawable.an3);
                mDataBinding.tvVideoSpeed2.setTextColor(Color.parseColor("#FFFFFF"));
                serSpeed(0.75f);
                break;
            case R.id.tvVideoSpeed3:
                clearSelect();
                mDataBinding.tvVideoSpeed3.setBackgroundResource(R.drawable.an3);
                mDataBinding.tvVideoSpeed3.setTextColor(Color.parseColor("#FFFFFF"));
                serSpeed(1.0f);
                break;
            case R.id.tvVideoSpeed4:
                clearSelect();
                mDataBinding.tvVideoSpeed4.setBackgroundResource(R.drawable.an3);
                mDataBinding.tvVideoSpeed4.setTextColor(Color.parseColor("#FFFFFF"));
                serSpeed(1.5f);
                break;
            case R.id.tvVideoSpeed5:
                clearSelect();
                mDataBinding.tvVideoSpeed5.setBackgroundResource(R.drawable.an3);
                mDataBinding.tvVideoSpeed5.setTextColor(Color.parseColor("#FFFFFF"));
                serSpeed(2.0f);
                break;
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
    }

    //保存视频
    private void saveVideo(String videoPath) {
        EditorHolder.editor().videoChangeSpeed(videoPath, currentSpeed, SpeedMode.ALL, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //保存到创作记录
                        String filePath = FileUtil.generateFilePath(Content.myRecord, "." + FileUtils.getFileExtension(outFilePath));
                        FileUtils.copy(outFilePath, filePath);
                        //保存到本地
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                    }

                    @Override
                    public void accept(String obj) {

                    }
                });
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_def));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.save_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //设置速度
    private void serSpeed(float speed) {
        currentSpeed = speed;
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                PlaybackParams playbackParams = mediaPlayer.getPlaybackParams();
                playbackParams.setSpeed(currentSpeed);
                mediaPlayer.setPlaybackParams(playbackParams);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
                startTime();
            }
        });
    }

    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_bf);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void clearSelect() {
        mDataBinding.tvVideoSpeed1.setBackgroundResource(R.drawable.an3a);
        mDataBinding.tvVideoSpeed1.setTextColor(Color.parseColor("#664F59"));
        mDataBinding.tvVideoSpeed2.setBackgroundResource(R.drawable.an3a);
        mDataBinding.tvVideoSpeed2.setTextColor(Color.parseColor("#664F59"));
        mDataBinding.tvVideoSpeed3.setBackgroundResource(R.drawable.an3a);
        mDataBinding.tvVideoSpeed3.setTextColor(Color.parseColor("#664F59"));
        mDataBinding.tvVideoSpeed4.setBackgroundResource(R.drawable.an3a);
        mDataBinding.tvVideoSpeed4.setTextColor(Color.parseColor("#664F59"));
        mDataBinding.tvVideoSpeed5.setBackgroundResource(R.drawable.an3a);
        mDataBinding.tvVideoSpeed5.setTextColor(Color.parseColor("#664F59"));
    }

}